<?php

namespace app\admin\controller\member;

use app\admin\model\UM as UM;
use app\admin\service\LawyerExportService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use response\Excel;
use think\APP;
use think\Collection;
use think\Request as Request;
use think\Response;

/**
 * LawyerBalanceExport 控制器
 * Class LawyerBalanceExport
 * @package app\admin\controller\member;
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037509
 * @see \app\admin\validate\member\LawyerBalanceExport
 */
class LawyerBalanceExport
{
    // 请求参数
    private Request $request;

    // service
    private LawyerExportService $service;

    public function __construct(Request $request, LawyerExportService $lawyerExportService)
    {
        $this->request = $request;
        $this->service = $lawyerExportService;
    }

    /**
     * 已入驻律师-导出
     * @param UM|null $user
     * @return Response
     * @url /member/lawyer_balance_export/index
     */
    public function index(?UM $user)
    {
        $request = $this->request;

        $card_balance = $request->param('card_balance', null);

        $collection = $this->service->indexBalance($user, $card_balance);

        $spreadsheet = new Spreadsheet();

        // 填数据
        $this->change($spreadsheet, $collection);

        $filename = '律师余额信息';

        return new Excel($spreadsheet, $filename);
    }

    // 填数据
    private function change(Spreadsheet $spreadsheet, Collection $collection): void
    {
        $sheet = $spreadsheet->getActiveSheet();

        //表头
        $i = 1;
        $sheet->setCellValue('A' . $i, 'UID')
            ->setCellValue('B' . $i, '昵称')
            ->setCellValue('C' . $i, '真实姓名')
            ->setCellValue('D' . $i, '类型')
            ->setCellValue('E' . $i, '城市')
            ->setCellValue('F' . $i, '余额')
            ->setCellValue('G' . $i, '获客卡余额')
            ->setCellValue('H' . $i, '通讯币余额');

        //  姓名，城市，余额，获客卡余额， 通讯比余额

        // 数据
        $collection->each(function (\app\common\model\Member $member, $key) use ($sheet, &$i) {
            $i++;
            $city = $member->city;

            $sheet->setCellValue('A' . $i, $member['id'])
                ->setCellValue('B' . $i, $member['nickname'])
                ->setCellValue('C' . $i, $member['realname'])
                ->setCellValue('D' . $i, $member['subType'] == 0 ? '律师' : '法务')
                ->setCellValue('E' . $i, $city ? $city['name'] : '')
                ->setCellValue('F' . $i, $member['accountBalance'])
                ->setCellValue('G' . $i, $member['cardBalance'])
                ->setCellValue('H' . $i, $member['coinBalance']);
        });


    }
}
